import { reqGetDepartments, reqGetDoctors, reqGetHospitalSchedule } from '@/api/hospital/hospitalList';
import { BookingScheduleItem, Department, DoctorItem } from '@/api/hospital/model/hospitalListTypes';
import { Breadcrumb, Button, Card, Col, Pagination, Row, Tag, Tree } from 'antd'
import Table, { ColumnsType } from 'antd/lib/table';
import { DataNode } from 'antd/lib/tree';
import React, { useEffect, useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom';

export default function HospitalSchedule() {
  //声明科室的状态
  let [departments, setDepartments] = useState<Department[]>([]);
  //声明展开节点的状态
  let [expandedKeys, setExpandedKeys] = useState<string[]>([]);
  //声明当前选中的科室状态
  let [depcode, setDepcode] = useState<string>('');
  //声明排班规则的状态
  let [schedules, setSchedules] = useState<BookingScheduleItem[]>([]);
  //声明与分页相关的状态
  let [current, setCurrent] = useState(1);
  let [pageSize, setPageSize] = useState(5);
  let [total, setTotal] = useState(0);
  //声明医生列表的状态
  let [doctors, setDoctors] = useState<DoctorItem[]>([]);
  //声明医院名称的状态
  let [hosname, setHosname] = useState<string>('');
  //声明科室名称的状态
  let [depname, setDepname] = useState<string>('');
  //声明排班日期的状态
  let [workDate, setWorkDate] = useState<string>('');
  //定义状态左侧侧边栏的高度
  let [height, setHeight] = useState(400);

  //定义表格的结构
  let columns: ColumnsType<DoctorItem> = [
    {
      title: '序号',
      render: (_, record, index) => {
        return index + 1;
      }
    },
    {
      title: '职称',
      dataIndex: 'title'
    },
    {
      title: '号源时间',
      dataIndex: 'workDate'
    },
    {
      title: '总预约数',
      dataIndex: 'reservedNumber'
    },
    {
      title: '剩余预约数',
      dataIndex: 'availableNumber'
    },
    {
      title: '挂号费',
      dataIndex: 'amount'
    },
    {
      title: '擅长技能',
      dataIndex: 'skill'
    }
  ];

  //接收传入的 state 参数
  let {state} = useLocation();
  //获取传入的医院的编号
  let hoscode = (state as any).hoscode;
  //获取navigate 函数
  let navigate = useNavigate();
  
  //声明 useEffect 回调发送请求
  useEffect(() => {
    let getDepartments = async () => {
      if(hoscode){
        //获取当前医院的科室
        let departments = await reqGetDepartments(hoscode);
        //使所有的一级科室不可点
        let result = departments.map(item => {
          //设置一级科室对象 disabled 属性为 真
          item.disabled = true;
          return item;
        });
        //更新 departments 的状态
        setDepartments(result);
        //获取所有一级科室的 id
        let ids = result.map(item => item.depcode);
        //更新展开节点的状态
        setExpandedKeys(ids);     
        //获取第一个一级科室中的第一个二级科室的 id
        let depcode = (result[0].children as Department[])[0].depcode;
        //获取第一个一级科室中的第一个二级科室的名称
        let depname = (result[0].children as Department[])[0].depname;
        //更新当前科室的状态
        setDepcode(depcode);
        setDepname(depname);
      }
    }
    getDepartments();
  }, []);

  //声明科室名称和编号发生变化的回调
  useEffect(() => {
    let getData = async () => {
      // 判断 depcode 的值, 如果为空字符串, 则直接返回, 不发请求
      if(!depcode) return;
      //获得当前医院 当前科室的排班规则
      let schedules = await reqGetHospitalSchedule({page: current, limit: pageSize, hoscode:hoscode, depcode: depcode });
      //更新排班规则的状态
      setSchedules(schedules.bookingScheduleList);
      //更新总数的状态
      setTotal(schedules.total);
      //更新医院名称的状态
      setHosname(schedules.baseMap.hosname);
      //声明一个变量 保存第一个排班规则的日期
      let workDate = schedules.bookingScheduleList[0].workDate;
      //更新 workDate 状态
      setWorkDate(workDate);
    };
    getData();
  }, [depcode, depname, current]);

  //声明 effect 回调
  useEffect(() => {
    let getData = async () => {
      //判断 workDate 的
      if(!workDate) return;
      //调用函数获取第一个规则日期的排班医生
      let doctors = await reqGetDoctors(hoscode, depcode, workDate);
      //更新医生列表的状态
      setDoctors(doctors);
    }
    getData();
  }, [workDate]);

  //声明 effect 回调为 window 绑定 resize 事件
  useEffect(() => {
    //声明一个函数
    let fn = () => {
      //获取当前视口的高度
      let h = document.documentElement.clientHeight; // widnow.innerHeight
      //计算左侧科室的高度
      let height = h - 64 - 34 - 24 * 2 - 19 - 20;
      //更新状态
      setHeight(height);
    };
    //绑定 resize 事件
    window.addEventListener('resize', fn);
    //组件挂载之后执行函数, 计算左侧的高度
    fn();
  }, [])

  return (
    <Card>
      {/* 路径导航 */}
      <Breadcrumb>
        <Breadcrumb.Item>选择: {hosname}</Breadcrumb.Item>
        <Breadcrumb.Item>
          {depname}
        </Breadcrumb.Item>
        <Breadcrumb.Item>
          {workDate}
        </Breadcrumb.Item>
      </Breadcrumb>
      <div className="h-20"></div>
      {/* 内容区 */}
      <Row gutter={30}>
        {/* 左侧列 */}
        <Col span={5} >
          <div style={{ border: 'solid 1px #ddd', height: height, overflowY:'scroll' }}>
            <Tree
              //展开节点的 id 列表
              expandedKeys={expandedKeys}
              //选中节点的 id
              selectedKeys={[depcode]}
              defaultCheckedKeys={['0-0-0', '0-0-1']}
              fieldNames={{
                title: 'depname',
                key: 'depcode'
              }}
              onSelect={async (selectedKeys, info: any) => {
                //获取科室的编号
                let depcode = info.node.depcode;
                //获取科室的名称
                let depname = info.node.depname;
                //更新状态
                setDepcode(depcode);
                setDepname(depname);
              }}
              // onCheck={onCheck}
              treeData={departments as []}
            />
          </div>
        </Col>

        {/* 右侧列 */}
        <Col span={19}>
          {/* 排班日期列表 */}
          <div>
            {
              schedules.map((item, index) => {
                return <Tag 
                      color={item.workDate === workDate ? 'green' : ''} 
                      key={index}
                      onClick={async () => {
                        //获取当前所点排班的日期
                        let workDate = item.workDate;
                        //更新日期状态
                        setWorkDate(workDate);   
                      }}
                      >
                  <div>{item.workDate} {item.dayOfWeek}</div>
                  <div>{item.availableNumber} / {item.reservedNumber}</div>
                </Tag>
              })
            }
          </div>
          <div className="h-20"></div>
          {/* 分页结构 */}
          <Pagination
            current={current}
            total={total}
            pageSize={pageSize}
            showSizeChanger={true}
            onChange={(page, pageSize) => {
              //更新页码和每页显示数量的状态
              setCurrent(page);
              setPageSize(pageSize);
            }}
          />
          <div className="h-20"></div>
          {/* 表格结构 */}
          <Table rowKey={'id'} columns={columns} dataSource={doctors} pagination={false} bordered />
          <div className="h-20"></div>
          <Button onClick={() => {
            navigate(-1);
          }}>返回</Button>

        </Col>
      </Row>
    </Card>
  )
}
